<template>
  <!-- 顶部返回吸顶条 -->
  <base-header :showButton="true" :backTextShow="true">
    <template #title>工作流审批</template>
    <template #header_btns>
      <el-button type="primary" @click="showOpinion(0)" v-if="processesData.policyDecisionList.includes('同意')">同意</el-button>
      <el-button plain type="warning" @click="showOpinion(1)" v-if="processesData.policyDecisionList.includes('拒绝')">拒绝</el-button>
      <el-button plain type="warning" @click="showOpinion(2)" v-if="processesData.policyDecisionList.includes('终止')">终止工作流</el-button>
    </template>
  </base-header>
  <div class="mt20">
    <el-row class="contract_base_title">流程单据名称：{{ docConfigName }}</el-row>
    <div class="tabAll">
      <el-tabs v-model="activeName" @tab-click="tabClickChange">
        <el-tab-pane label="单据详情" name="1"></el-tab-pane>
        <el-tab-pane label="会审详情" name="2"></el-tab-pane>
        <el-tab-pane label="审批记录" name="3"></el-tab-pane>
        <el-tab-pane label="流程图" name="4"></el-tab-pane>
      </el-tabs>
    </div>

    <div v-if="activeName == '1'">
      <component :is="current.com" v-if="componentShow" :componentObject="componentObject" :docConfigLineList="docConfigLineList"></component>
    </div>
    <div v-else-if="activeName == '2'">
      <el-form ref="drawerform" label-position="left">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="审批模式：" prop="fieldCode">
              <span v-if="approverType">{{ approverType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="ratio">
            <el-form-item label="通过比例：" prop="fieldName">
              <span>{{ ratio * 100 }}%</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        ref="drawermultipleTable"
        :data="drawerTableData"
        tooltip-effect="dark"
        :style="drawerTableData.length == 0 ? 'height:100px;' : ''"
        border
      >
        <el-table-column label="审批人" prop="assigneeName" show-overflow-tooltip></el-table-column>
        <el-table-column label="审批结果" prop="approveResult" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.approveResult == 1 ? '同意' : row.approveResult == 1 ? '拒绝' : '' }}
          </template>
        </el-table-column>
        <el-table-column label="审批意见" prop="comment" show-overflow-tooltip> </el-table-column>
        <el-table-column label="审批时间" prop="finishTime" show-overflow-tooltip></el-table-column>
      </el-table>
    </div>
    <div v-else-if="activeName == '3'">
      <processes-table ref="processesTableChild" :tableData="tableData"></processes-table>
    </div>
    <div v-if="(activeName == '4' || !showBpmn) && xmlStr" :class="!showBpmn ? 'showBpmn' : ''">
      <processes-bpmn
        ref="processesBpmnChild"
        :xmlStr="xmlStr"
        :flowViewerList="flowViewerList"
        :flowViewMapId="taskDefKey"
        :bpmnHeight="'calc(80vh - 130px)'"
        @processesData="proData"
      ></processes-bpmn>
    </div>

    <!-- 审批意见弹板 -->
    <zcb-dialog title="审批意见" width="744px" v-model="isShowDialog" append-to-body destroy-on-close :close-on-click-modal="false">
      <template #btns>
        <el-button @click="isShowDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoaging" @click="handlsubmitForm(dialogformChild)">确定</el-button>
      </template>

      <el-form v-if="isShowDialog" ref="dialogformChild" :rules="dialogrules" :model="dialogform" label-position="left">
        <el-form-item prop="description" label="">
          <el-input
            :rows="5"
            type="textarea"
            placeholder="请输入审批意见"
            resize="none"
            v-model.trim="dialogform.description"
            maxlength="120"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>
    </zcb-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, markRaw, defineAsyncComponent } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ERR_OK } from 'config/statusCode'
import baseHeader from 'components/base-header'
import processesTable from 'components/processes-table'
import processesBpmn from 'components/processes-bpmn'
import { flowtaskDetail, flowtaskProcessVariables, flowtaskComplete, flowtaskReject, flowtaskTermination } from 'api/personalCenter'
import { docConfigCodelineList } from 'api/personalCenter'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文
const router = useRouter()
const route = useRoute()

// 定义初始组件
let current = reactive({
  com: markRaw(defineAsyncComponent(() => import(`views/personalCenter/componentForm/test.vue`)))
})
// 切换组件
const switchComponent = (component) => {
  current.com = markRaw(defineAsyncComponent(() => import(`views/personalCenter/componentForm/${component}.vue`)))
}

const processInstanceId = ref('')
const taskDefKey = ref('')
const approverType = ref('')
const drawerTableData = ref([])
const tableData = ref([])
const xmlStr = ref('')
const ratio = ref(0)
const flowViewerList = ref([])

const getdetails = async () => {
  const { code, data } = await flowtaskDetail(processInstanceId.value, { taskDefKey: taskDefKey.value })
  if (code === ERR_OK) {
    approverType.value = data.approverType || ''
    ratio.value = Number(data.ratio) || 0
    drawerTableData.value = data.flowTaskList || []
    tableData.value = data.flowTaskRecords || []
    xmlStr.value = data.processXml || ''

    let flowViewMap = data.flowViewMap || [] // 走完的节点
    var flowViewMapArr = []
    for (let i = 0; i < Object.keys(flowViewMap).length; i++) {
      flowViewMapArr.push({ key: Object.keys(flowViewMap)[i], completed: flowViewMap[Object.keys(flowViewMap)[i]] })
    }
    flowViewerList.value = flowViewMapArr

    tableData.value.forEach((item) => {
      item.assigneeName = item.assigneeNameList ? item.assigneeNameList.toString() : ''
      item.assigneeNameListLength = item.assigneeNameList ? item.assigneeNameList.length : 0
    })
  }
}

const docConfigCode = ref('')
const docConfigLineList = ref([])
const componentObject = reactive({})
const componentShow = ref(false)

const getflowtaskProcessVariables = async () => {
  // 单据流程渲染数据
  const { code, data } = await docConfigCodelineList({ docConfigCode: docConfigCode.value })
  if (code === ERR_OK) {
    let docList = data.docConfigLineList || []
    docConfigLineList.value = JSON.parse(JSON.stringify(docList))
  }

  const { codes, datas } = await flowtaskProcessVariables(processInstanceId.value)
  if (codes === ERR_OK) {
    componentObject = datas || {}
  }
  componentShow.value = true
}

const activeName = ref('1')
const showBpmn = ref(false)
const tabClickChange = (tab, event) => {
  showBpmn.value = false
  if (tab.paneName == '4') {
    showBpmn.value = true
  }
}

const processesData = reactive({
  policyDecisionList: [], // 决策项
  ApprovalOpinionsFlag: true, // 审批意见
  ApprovalOpinionsList: '' // 审批意见必填
})
const isShowDialog = ref(false)
const dialogrules = reactive({
  description: [{ required: true, message: `审批意见不能为空！`, trigger: 'blur' }]
})
const dialogform = reactive({
  description: ''
})
const handlNum = ref('')

const showOpinion = (num) => {
  dialogform.description = ''
  if (processesData.ApprovalOpinionsFlag) {
    handlNum.value = num
    if (num == 0 && processesData.ApprovalOpinionsList.includes('同意时')) {
      // 审批
      isShowDialog.value = true
      return
    } else if (num == 1 && processesData.ApprovalOpinionsList.includes('拒绝时')) {
      isShowDialog.value = true
      return
    } else if (num == 2 && processesData.ApprovalOpinionsList.includes('终止时')) {
      isShowDialog.value = true
      return
    }

    ElMessageBox.confirm(`${num == 0 ? `确认同意流程吗？` : num == 1 ? `确认拒绝流程吗？` : '确认终止工作流吗？'}`, t('keys.tips'), {
      distinguishCancelAndClose: true,
      confirmButtonText: t('keys.ok'),
      cancelButtonText: t('keys.cancel')
    }).then(() => {
      if (num == 0) {
        // 审批
        setFlowtaskComplete()
      } else if (num == 1) {
        setFlowtaskReject()
      } else if (num == 2) {
        setFlowtaskTermination()
      }
    })
  } else {
    ElMessageBox.confirm(`${num == 0 ? `确认同意流程吗？` : num == 1 ? `确认拒绝流程吗？` : '确认终止工作流吗？'}`, t('keys.tips'), {
      distinguishCancelAndClose: true,
      confirmButtonText: t('keys.ok'),
      cancelButtonText: t('keys.cancel')
    }).then(() => {
      if (num == 0) {
        // 审批
        setFlowtaskComplete()
      } else if (num == 1) {
        setFlowtaskReject()
      } else if (num == 2) {
        setFlowtaskTermination()
      }
    })
  }
}
const submitLoaging = ref(false)
const dialogformChild = ref(null)
const handlsubmitForm = async (formEl) => {
  // 保存头信息
  if (!formEl) return
  submitLoaging.value = true
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (handlNum.value == 0) {
        // 审批
        setFlowtaskComplete()
      } else if (handlNum.value == 1) {
        setFlowtaskReject()
      } else if (handlNum.value == 2) {
        setFlowtaskTermination()
      }
      return
    } else {
      return false
    }
  })
}

const taskId = ref('')
const setFlowtaskComplete = async () => {
  // 审批任务
  let param = {
    processInstanceId: processInstanceId.value,
    taskId: taskId.value,
    comment: dialogform.description
  }
  const { code, data } = await flowtaskComplete(param)
  if (code === ERR_OK) {
    isShowDialog.value = false
    ElMessage({
      message: '审批任务成功',
      type: 'success'
    })
    router.replace({
      name: 'myAgent'
    })
  }
  submitLoaging.value = false
}

const setFlowtaskReject = async () => {
  // 拒绝任务
  let param = {
    processInstanceId: processInstanceId.value,
    taskId: taskId.value,
    comment: dialogform.description
  }
  const { code, data } = await flowtaskReject(param)
  if (code === ERR_OK) {
    isShowDialog.value = false
    ElMessage({
      message: '拒绝任务成功',
      type: 'success'
    })
    router.replace({
      name: 'myAgent'
    })
  }
  submitLoaging.value = false
}

const setFlowtaskTermination = async () => {
  // 终止任务
  let param = {
    processInstanceId: processInstanceId.value,
    taskId: taskId.value,
    comment: dialogform.description
  }
  const { code, data } = flowtaskTermination(param)
  if (code === ERR_OK) {
    isShowDialog.value = false
    ElMessage({
      message: '终止任务成功',
      type: 'success'
    })
    router.replace({
      name: 'myAgent'
    })
  }
  submitLoaging.value = false
}

const proData = (val) => {
  // 获取审批、拒绝、终止工作流
  processesData.ApprovalOpinionsFlag = val.ApprovalOpinionsFlag
  processesData.ApprovalOpinionsList = val.ApprovalOpinionsList || []
  processesData.policyDecisionList = val.policyDecisionList || []
}

const docConfigName = ref('')
const fromUrl = ref('')
onMounted(() => {
  docConfigCode.value = route.query.docConfigCode || ''
  docConfigName.value = route.query.docConfigName || ''
  fromUrl.value = route.query.fromUrl || ''
  taskId.value = route.query.taskId || ''
  taskDefKey.value = route.query.taskDefKey || ''
  processInstanceId.value = route.query.processInstanceId || ''
  if (processInstanceId.value) {
    getdetails()
  }
  getflowtaskProcessVariables()
  switchComponent(fromUrl.value)
})
</script>
<style lang="scss" scoped>
.mt20 {
  margin-top: 20px;
}
.showBpmn {
  position: fixed;
  top: 1000000px;
  right: 1000000px;
  z-index: -10;
}
.dialogbtn {
  text-align: center;
}
</style>
